import { defineStore } from 'pinia';
import request from '@/utils/request';
import { router } from '@/router';
import MainRoutes from '@/router/MainRoutes';
import { tokenName } from '@/config/index';
import { useAuthStore } from '@/stores/auth';
import FullLayout from '@/layouts/full/FullLayout.vue';
import BlankLayout from '@/layouts/blank/BlankLayout.vue';
import { getStorage, setStorage, removeStorage } from '@/utils/storage';
import type { RouteRecordRaw } from 'vue-router';

const layoutMap: Record<string, any> = {
  'Layout': FullLayout,
  'BlankLayout': BlankLayout,
};

interface RouteItem {
  path: string;
  name?: string;
  component?: any;
  meta?: {
    title?: string;
    icon?: string;
    permissions?: string[];
    affix?: boolean;
    requiresAuth?: boolean;
    [key: string]: any;
  };
  children?: RouteItem[];
  [key: string]: any;
}

// 将后端返回的菜单数据转换为路由格式
function convertMenuToRoute(menu: any, parentPath = ''): RouteItem {
  let component;

  if (menu.component && menu.component !== 'Layout' && menu.component !== 'BlankLayout' && menu.component !== 'EmptyLayout') {
    // 只处理页面组件，不处理 Layout 组件（因为 MainRoutes 已经提供了布局）
    component = () => import(`../${menu.component.endsWith('.vue') ? menu.component : menu.component + '.vue'}`);

  } else {
    // console.log(`跳过 Layout 组件或无组件: ${menu.component || '无'}`);
  }


  // 处理路径拼接
  let fullPath = menu.path;
  if (parentPath && !menu.path.startsWith('/')) {
    fullPath = `${parentPath}/${menu.path}`;
  }

  return {
    path: fullPath || '',
    name: menu.name,
    component,
    meta: {
      title: menu.meta?.title || menu.title,
      icon: menu.meta?.icon || menu.icon,
      permissions: menu.permissions,
      affix: menu.affix,
      requiresAuth: menu.requiresAuth
    },
    children: menu.children ? menu.children.map((child: any) => convertMenuToRoute(child, fullPath)) : undefined
  };
}

export const useMenuStore = defineStore({
  id: 'menu',
  state: () => {
    // console.log('=== Menu Store 初始化 ===');
    const routes = getStorage('opsli-routes') || [];
    const menus = getStorage('opsli-menus') || [];

    // console.log('从缓存读取的菜单数据:');
    // console.log('- routes数量:', routes.length);
    // console.log('- menus数量:', menus.length);
    // console.log('- routes详情:', routes);
    // console.log('- menus详情:', menus);

    return {
      routes,
      menus,
      isFirstLoad: true
    };
  },
  actions: {
    /**
     * 从缓存恢复路由
     */
    restoreRoutesFromCache() {
      // console.log('=== 开始从缓存恢复路由 ===');
      // console.log('缓存中的菜单数量:', this.menus.length);
      // console.log('缓存中的菜单数据:', this.menus);

      if (this.menus.length > 0) {
        // console.log('从缓存恢复路由注册...');
        // 重新从菜单数据生成路由（因为 component 函数无法序列化）
        const accessRoutes = this.menus.map((menu: any) => {
          // console.log('转换菜单到路由:', menu.title, menu.path, menu);
          const route = convertMenuToRoute(menu);
          // console.log('转换后的路由:', route);
          return route;
        });
        // console.log('生成的访问路由:', accessRoutes);
        // 只用动态 accessRoutes 覆盖 MainRoutes.children
        this.routes = accessRoutes;
        // console.log('更新store中的routes完成');
        // 将路由添加到 MainRoutes 的 children 中
        MainRoutes.children = accessRoutes as any;
        //添加静态路由
        if (!MainRoutes.children) {
          MainRoutes.children = [];
        }
        MainRoutes.children.push({
          path: 'user/profile',
          name: 'UserProfile',
          component: () => import('@/views/user/Profile.vue'),
          meta: { requiresAuth: true, title: '个人信息' }
        });
        // console.log('设置MainRoutes.children完成');
        // 注册前先移除，避免重复
        const mainRouteName = MainRoutes.name || 'main';
        // console.log('检查是否存在主路由:', mainRouteName, router.hasRoute(mainRouteName));
        if (router.hasRoute(mainRouteName)) {
          // console.log('移除已存在的主路由');
          router.removeRoute(mainRouteName);
        }
        router.addRoute(MainRoutes);
        return true;
      } else {
        console.log('❌ 缓存中没有菜单数据，无法恢复路由');
        return false;
      }
    },
    /**
     * 获取菜单路由
     */
    async getRouterList() {
      const authStore = useAuthStore();
      try {
        const response = await request({
          url: '/api/v1/system/menu/findMenuTree',
          method: 'post',
          headers: {
            [tokenName]: authStore.accessToken
          }
        });

        if (response && response.data) {
          // 处理菜单数据
          this.menus = response.data;

          // 将菜单数据转换为路由格式
          const accessRoutes = this.menus.map((menu: any) => convertMenuToRoute(menu));

          // 更新路由
          this.routes = accessRoutes;

          // 持久化菜单和路由数据
          setStorage('opsli-menus', this.menus);
          setStorage('opsli-routes', this.routes);

          // 将路由添加到 MainRoutes 的 children 中
          MainRoutes.children = accessRoutes as any;

          // 注册前先移除，避免重复
          if (router.hasRoute(MainRoutes.name || 'main')) {
            router.removeRoute(MainRoutes.name || 'main');
          }
          router.addRoute(MainRoutes);

          // 调试：查看注册后的路由
          // console.log('注册的路由:', MainRoutes);
          console.log('所有路由:', router.getRoutes());

          return accessRoutes;
        }
        return [];
      } catch (error) {
        console.error('获取菜单失败', error);
        return [];
      }
    },

    /**
     * 重置路由
     */
    resetRoutes() {
      this.routes = [];
      this.menus = [];

      // 清除持久化数据
      removeStorage('opsli-menus');
      removeStorage('opsli-routes');

      // 移除动态添加的路由
      if (router.hasRoute(MainRoutes.name || 'main')) {
        router.removeRoute(MainRoutes.name || 'main');
      }
    }
  }
});